import tables, strutils

type
  RefLines* = ref CmrLines
  CmrLines = Table[string, string]

proc condAdd*(s: var string, condition: bool, s2: string) =
  if condition:
    s &= s2

proc stripUntil*(s: var string, token: char) =
  var
    charBuffer: char
    stringBuffer: string
  
  for i in 0 .. s.len - 1:
    charBuffer = s[i]
    if charBuffer == token:
      s = stringBuffer
      break

    stringBuffer.add charBuffer

# overload for searching strings
proc stripUntil*(s: var string, token: string) =
  let searchResult: int = rfind(s, token)
  var stringBuffer: string

  if searchResult > 0:
    for i in 0 .. searchResult - 1:
      stringBuffer &= s[i]

    s = stringBuffer

proc splitFirst*(s: string, token: char = ' '): (string, string) =
  var
    charBuffer: char
    afterToken: bool = false

  result = ("", "")
  
  for i in 0 .. s.len - 1:
    charBuffer = s[i]
    
    if charBuffer == token and not afterToken:
      afterToken = true
      continue

    if afterToken: result[1].add charBuffer
    else: result[0].add charBuffer

proc trySet*(s: var string, setTo: RefLines, field: string, fallback: string) =
  try: s = setTo[field]
  except: s = fallback

proc removePrefix*(s: var string, prefix: string, untilSpace: bool = true) =
  for c in prefix:
    if c in Whitespace and untilSpace: return
    s = s.strip(trailing = false, chars = {c})
